﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Web.Mail;
using System.Diagnostics;
using System.Data.SqlClient;

namespace SurveySystem.Core
{
    public static class CommunicationUtils
    {
        public static void HandleEmailsOnNewSurvey(Survey survey, SurveySystemDataContext dc)
        {
            string choices = survey.GetChoicesMessage(true);
            string desc = CommonUtils.MessageResources.GetString("EmailContent_" + survey.surveyType);
            foreach (User user in survey.GetParticipatingUsers(dc))
            {
                if (user.getEmailOnNewSurvey && survey.sendEmailOnCreation)
                {

                    string message = string.Format(CommonUtils.MessageResources.GetString("NewSurveyEmailMessage"),
                        string.IsNullOrEmpty(user.fullName) ? user.name : user.fullName,
                        survey.question,
                        desc,
                        choices);
                    SendEmail(user, String.Format(CommonUtils.MessageResources.GetString("NewSurveyEmailSubject"), survey.id), message);
                }
            }
        }

        public static void HandleSMSOnNewSurvey(Survey survey, SurveySystemDataContext dc)
        {
            string choices = survey.GetChoicesMessage(false);
            string desc = CommonUtils.MessageResources.GetString("SMSContent_" + survey.surveyType);
            foreach (User user in survey.GetParticipatingUsers(dc))
            {
                if (user.getSmsOnNewSurvey && survey.sendSmsOnCreation)
                {
                    string message = string.Format(CommonUtils.MessageResources.GetString("NewSurveySMSMessage"),
                        survey.question,
                        desc,
                        choices,
                        survey.id);
                    SendSMS(user, message);
                }
            }
        }

        public static void HandleEmailsOnExpiredSurvey(Survey survey, SurveySystemDataContext dc)
        {
            string choices = survey.GetChoicesSummaryMessage(true);
            string desc = CommonUtils.MessageResources.GetString("FEmailContent_" + survey.surveyType);
            foreach (User user in survey.GetParticipatingUsers(dc))
            {
                if (user.getEmailOnExpiration && survey.sendEmailOnExpiration)
                {

                    string message = string.Format(CommonUtils.MessageResources.GetString("ExpiredSurveyEmailMessage"),
                        string.IsNullOrEmpty(user.fullName) ? user.name : user.fullName,
                        survey.question,
                        desc,
                        choices);
                    SendEmail(user, CommonUtils.MessageResources.GetString("ExpiredSurveyEmailSubject"), message);
                }
            }
        }

        public static void HandleSMSOnExpiredSurvey(Survey survey, SurveySystemDataContext dc)
        {
            string choices = survey.GetChoicesSummaryMessage(false);
             string desc = CommonUtils.MessageResources.GetString("FEmailContent_" + survey.surveyType);
             foreach (User user in survey.GetParticipatingUsers(dc))
             {
                 if (user.getEmailOnExpiration && survey.sendSmsOnExpiration)
                 {
                     string message = string.Format(CommonUtils.MessageResources.GetString("ExpiredSurveySMSMessage"),
                         survey.question,
                         desc,
                         choices);
                     SendSMS(user, message);
                     }
             }
        }

        public static void SendEmail(User user, string subject, string message)
        {
            try
            {
                //Debug.Print(SmtpMail.SmtpServer);
                //SmtpMail.Send(CommonUtils.ApplicationEmailAddress, user.email, subject, message);

                SmtpClient smtp = new SmtpClient();
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(CommonUtils.ApplicationEmailAddress, user.email, subject, message);
                mail.IsBodyHtml = true;
                smtp.Send(mail);
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
            }
        }

        public static void SendSMS(User u, string message)
        {
            SqlConnection conn = new SqlConnection(CommonUtils.OzekiConnectionString);
            conn.Open();
            SqlCommand cmd = new SqlCommand(String.Format("INSERT INTO ozekimessageout (receiver,msg,status) VALUES ('{0}','{1}','Send');",u.mobile,message), conn);
            cmd.ExecuteNonQuery();
            conn.Close();
        }

        public static void HandleNewSMS(string from, string message)
        {
            User user = UsersBLL.GetUserByMobile(from);
            int surveyId = -1;
            try
            {
                if (!Int32.TryParse(message.Substring(0, message.IndexOf('-') - 1), out surveyId))
                {
                    Debug.Print("SMS hiba");
                    return;
                }
            }
            catch
            {
                Debug.Print("SMS hiba");
                return;
            }
            Survey s = SurveysBLL.GetSurvey(surveyId);
            string str = message.Substring(message.IndexOf('-') + 1);
            HandleMsgBody(s, user, str);
        }

        public static void HandleNewEmail(string from, string subject, string message)
        {
            User user = UsersBLL.GetUserByEmail(from);
            int surveyId = -1;
            if (!Int32.TryParse(subject.Substring(subject.LastIndexOf('-') + 2), out surveyId))
            {
                Debug.Print("Email hiba");
                return;
            }
            Survey s = SurveysBLL.GetSurvey(surveyId);
            HandleMsgBody(s, user, message);
        }

        public static void HandleMsgBody(Survey s, User u, string body)
        {
            if (s.surveyType == SurveyType.Free)
            {
                SurveysBLL.AddFreeAnswer(s.id, u.name, body);
            }
            if (s.surveyType == SurveyType.Choice)
            {
                string msg = body.Trim();
                char c = ' ';
                for (int i = 0; i < msg.Length; i++)
                {
                    if (msg[i] >= 'A' && msg[i] <= 'Z' || msg[i] >= 'a' && msg[i] <= 'z')
                    {
                        c = Char.ToUpper(msg[i]);
                        break;
                    }
                }
                try
                {
                    Choice choice = s.Choices.First(ch => ch.letter == c);
                    if (choice == null)
                    {
                        Debug.Print("Invalid letter");
                    }
                    SurveysBLL.AddChoiceAnswer(s.id, u.name, choice.id);
                }
                catch {
                    Debug.Print("Invalid letter");
                }
            
            }
            else if (s.surveyType == SurveyType.MultiChoice)
            {
                string msg = body.Trim();
                string[] parts = msg.Split(',');
                List<int> choiceIds = new List<int>();
                foreach (string str in parts)
                {
                    char c = ' ';
                    for (int i = 0; i < str.Length; i++)
                    {
                        if (str[i] >= 'A' && str[i] <= 'Z' || str[i] >= 'a' && str[i] <= 'z')
                        {
                            c = Char.ToUpper(str[i]);
                            break;
                        }
                    }

                    if (c != ' ')
                    {
                        try
                        {
                            int choiceId = s.Choices.First(ch => ch.letter == c).id;
                            if (!choiceIds.Contains(choiceId))
                                choiceIds.Add(choiceId);    
                        }
                        catch { Debug.Print("Invalid letter!"); }

                    }

                }
                SurveysBLL.AddMultiAnwers(s.id, u.name, choiceIds);
            }
        }
    }
}
